package file

import (
	"crypto/md5"
	"encoding/hex"
	// "fmt"
	"hash/crc32"
	"io"
	"os"
	// "strconv"
	"strings"
)

type HexCodings []byte
type StringCodings string
type IntCodings uint32

func (f *File) GetFileStringCodings(types string) (cd StringCodings) {
	if f.Code == nil {
		f.Code = make(map[string]StringCodings)
	}
	if f == nil {
		return
	}
	pathname := f.Path + "/" + f.Name

	if strings.Compare(types, "MD5") == 0 {
		cd = StringCodings(hex.EncodeToString(GetFileMD5(pathname)))
		f.Code["MD5"] = cd
		// fmt.Println(cd)
	} else if strings.Compare(types, "CRC32") == 0 {
		cd = StringCodings(hex.EncodeToString(GetFileCRC32(pathname)))
		// fmt.Println(cd)
		f.Code["CRC32"] = cd
	}
	// if strings.Compare(types, "MD5") == 0 {
	// 	md5c := GetFileMD5(f.Path + "/" + f.Name)
	// 	f.Code["MD5"] = md5c
	// }
	// cd = md5c
	return
}

func GetFileMD5(pathname string) (cd HexCodings) {
	// fmt.Println("MD5:", pathname)
	file, inerr := os.Open(pathname)
	if inerr == nil {
		md5h := md5.New()
		io.Copy(md5h, file)
		cd = HexCodings(md5h.Sum(nil))
	} else {
		cd = HexCodings("")
	}
	// fmt.Printf("%x\n", cd) //md5

	return
}

func GetFileCRC32(pathname string) (cd HexCodings) {
	crc32q := crc32.MakeTable(0xD5828281)
	file, inerr := os.Open(pathname)
	if inerr == nil {
		// fmt.Println("crc32")
		crc32c := crc32.New(crc32q)
		// crc32c := crc32.
		io.Copy(crc32c, file)
		cd = HexCodings(crc32c.Sum(nil))
	} else {
		cd = HexCodings("")
	}
	return
}
